package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.UserApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.UserApi;
import com.cuckoo.cuckoo_app2.business.Imp.UserBusinessImp;
import com.cuckoo.cuckoo_app2.business.UserBusiness;
import com.cuckoo.cuckoo_app2.dao.SysUser;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.model.JavaScriptResponseModel;

import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.MessageCodeUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MaskLoginActivity extends AppCompatActivity {

    Context context;
    ViewHolder holder;
    JavaScriptResponseModel responseModelG;
    private Integer mode = 2;
    private String checkKey;
    private UserApi userApi;
    private Integer color_grey;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_login);
        this.context = this;
        this.userApi = new UserApiImp();

        holder = new ViewHolder();

        this.color_grey = ContextCompat.getColor(context, R.color.text_grey);
        this.initView();
        this.onClickButton();
    }

    private void initView() {

        holder.login_username.setVisibility(View.GONE);
        holder.login_password.setVisibility(View.GONE);
        holder.login_phone.setVisibility(View.GONE);

        holder.login_Code.setVisibility(View.GONE);

        holder.login_button.setVisibility(View.GONE);
        holder.login_button_getCode.setVisibility(View.GONE);
        holder.login_button_register.setVisibility(View.GONE);
        holder.register_code.setVisibility(View.GONE);

        // 默认模式 2登录  1注册
        if (mode == 2) {
            holder.login_title.setText("登录");
            holder.login_username.setVisibility(View.VISIBLE);
            holder.login_password.setVisibility(View.VISIBLE);

            holder.login_button.setVisibility(View.VISIBLE);
            holder.login_button.setText("登录");

            holder.login_button_register.setVisibility(View.VISIBLE);
            holder.login_button_register.setText("注册");

        } else {
            holder.login_title.setText("注册");
            holder.login_username.setVisibility(View.VISIBLE);
            holder.login_password.setVisibility(View.VISIBLE);
            holder.login_phone.setVisibility(View.VISIBLE);

            holder.login_Code.setVisibility(View.VISIBLE);
            holder.login_button_getCode.setVisibility(View.VISIBLE);

            holder.register_code.setVisibility(View.VISIBLE);

            holder.login_button.setVisibility(View.VISIBLE);
            holder.login_button.setText("注册");

            holder.login_button_register.setVisibility(View.VISIBLE);
            holder.login_button_register.setText("登录");
        }
    }

    private void onClickButton() {
        // 点击切换模式
        holder.login_button_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mode == 2) {
                    mode = 1;
                } else {
                    mode = 2;
                }
                initView();
            }
        });

        // 获取手机验证码
        holder.login_button_getCode.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onGetPhoneCode();
            }
        });

        // 点击确认按钮
        holder.login_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onSubmit();
            }
        });
    }

    /**
     * 发送手机验证码
     */
    public void onGetPhoneCode() {
        String mobile = holder.login_phone.getText().toString();
        if (mobile.equals("")) {
            DialogUtils.showToast(context, "请输入手机号");
            return;
        }

        userApi.performGetPhoneCodeAsync(mobile, mode.toString(), new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, data.get("message").getAsString());
                        }
                    });
                    return;
                }
                holder.login_button_getCode.setText("已发送");
                holder.login_button_getCode.setBackgroundColor(color_grey);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.showToast(context, "验证码已发送");
                    }
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.showToast(context, "验证码请求失败");
                    }
                });
            }
        });
    }

    /**
     * 提交案
     */
    public void onSubmit() {
        String username = holder.login_username.getText().toString();
        String password = holder.login_password.getText().toString();
        String code = holder.login_Code.getText().toString();
        String phone = holder.login_phone.getText().toString();
        String registerCode = holder.register_code.getText().toString();

        // 注册 账号  密码 手机号 验证码
        if (username.equals(null) || username.equals("")) {
            DialogUtils.showToast(context, "用户名不能为空");
            return;
        }
        if (password.equals(null) || password.equals("")) {
            DialogUtils.showToast(context, "密码不能为空");
            return;
        }
        if (mode == 2) {
            // 登录  账号  密码
            userApi.performLoginAsync(username, password, new BaseCallbac<JsonObject>() {
                @Override
                public void onSuccess(JsonObject data) {
                    if (!data.get("success").getAsBoolean()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                DialogUtils.showToast(context, data.get("message").getAsString());
                            }
                        });
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    String token = result.get("token").getAsString();

                    // vipInfo
                    JsonObject vipInfo = result.get("vipInfo").getAsJsonObject();
                    String isVip = vipInfo.get("isVip").getAsString();
                    String vipEndTime = vipInfo.get("endVip").getAsString();

                    // 用户信息
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                    SysUser sysUser = gson.fromJson(result.get("userInfo"), SysUser.class);

                    User user = new User();
                    user.setId(sysUser.getId());
                    user.setName(sysUser.getUsername());
                    user.setPhone(sysUser.getPhone());
                    user.setPassword(password);
                    user.setImgUrl(sysUser.getAvatar());
                    user.setAddTime(sysUser.getCreateTime());
                    user.setToken(token);
                    user.setIsVip(Integer.parseInt(isVip));

                    try {
                        Date date = sdf.parse(vipEndTime);
                        user.setEndVip(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    UserBusiness userBusiness = new UserBusinessImp();
                    userBusiness.saveLoginInfo(user);
                    MyApplication.getInstances().clearUser();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, "登录成功");
                        }
                    });

                    // 发送刷新信息
                    Messenger mMessenger = MyApplication.getInstances().getMessage();
                    Message message = Message.obtain();
                    message.what = MessageCodeUtils.UPDATE_BACKGROUND_DATA.getCode();
                    try {
                        mMessenger.send(message);
                    } catch (RemoteException e) {
                        Log.e("TEST", e.getMessage());
                    }

                    // 暂停一秒
                    DialogUtils.sleep(1000);
                    // 返回上一页
                    finish();
                }

                @Override
                public void onFailure(String errorMessage) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, "服务器请求失败");
                        }
                    });
                }
            });

        } else {

            if (code.equals(null) || code.equals("")) {
                DialogUtils.showToast(context, "验证码不能为空");
                return;
            }

            if (phone.equals(null) || phone.equals("")) {
                DialogUtils.showToast(context, "手机号不能为空");
                return;
            }
            if (registerCode.equals(null) || registerCode.equals("")) {
                DialogUtils.showToast(context, "邀请码不能为空");
                return;
            }

            userApi.performRegisterAsync(username, password, phone, code, registerCode, new BaseCallbac<JsonObject>() {

                @Override
                public void onSuccess(JsonObject data) {
                    if (!data.get("success").getAsBoolean()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                DialogUtils.showToast(context, data.get("message").getAsString());
                            }
                        });
                        return;
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, "注册成功");
                        }
                    });
                }

                @Override
                public void onFailure(String errorMessage) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, "服务器请求失败");
                        }
                    });
                }
            });
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 获取相应的ID
     */
    class ViewHolder {
        TextView login_title, login_button_register;
        EditText login_username, login_password, login_Code, login_phone, register_code;
        Button login_button, login_button_getCode;

        public ViewHolder() {
            this.login_title = findViewById(R.id.login_title);
            this.login_username = findViewById(R.id.login_username);
            this.login_password = findViewById(R.id.login_password);
            this.login_button = findViewById(R.id.login_button);
            this.login_Code = findViewById(R.id.login_Code);
            this.login_phone = findViewById(R.id.login_phone);
            this.login_button_getCode = findViewById(R.id.login_button_getCode);
            this.login_button_register = findViewById(R.id.login_button_register);
            this.register_code = findViewById(R.id.register_code);
        }
    }

}
